<template>
  <div style="padding: 10px; margin-bottom: 50px">
    <el-row>
      <el-col :span="8">
        <el-card style="width: 100%; min-height: 300px; color: #333">
          <div style="padding-bottom: 10px; border-bottom: 1px solid #ccc">在线用户<span style="font-size: 12px">（点击聊天气泡开始聊天）</span></div>
          <div style="padding: 10px 0" v-for="user in users" :key="user.username">
            <span>{{ user.username }}</span>
            <el-button
              type="text"
              icon="ChatRound"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="chatUser = user.username"
            ></el-button>
            <span style="font-size: 12px;color: limegreen; margin-left: 5px" v-if="user.username === chatUser">chatting...</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="16">
        <div style="width: 750px; margin: 0 auto; background-color: white;
                    border-radius: 5px; box-shadow: 0 0 10px #ccc">
          <div style="text-align: center; line-height: 50px;">
            Web聊天室（{{ chatUser }}）
          </div>
          <div style="height: 350px; overflow:auto; border-top: 1px solid #ccc" v-html="content"></div>
          <div style="height: 200px">
            <textarea v-model="text" style="height: 150px;width: 99%; border: none; border-top: 1px solid #ccc;
             border-bottom: 1px solid #ccc; resize: none; outline: none"
             @keydown.enter="send"></textarea>
            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send">发送</el-button>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
//用户名
const username = sessionStorage.getItem("user");

const socket = ref(null);
const circleUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png');
const user = ref({});
const isCollapse = ref(false);
const users = ref([]);
const chatUser = ref('');
const text = ref("");
const messages = ref([]);
const content = ref('');

const send = () => {
  if (!chatUser.value) {
    ElMessage({ type: 'warning', message: "请选择聊天对象" });
    return;
  }
  if (!text.value) {
    ElMessage({ type: 'warning', message: "请输入内容" });
  } else {
    if (typeof WebSocket === "undefined") {
      console.log("您的浏览器不支持WebSocket");
    } else {
      console.log("您的浏览器支持WebSocket");
      let message = { from: username, to: chatUser.value, text: text.value };
      socket.value.send(JSON.stringify(message));
      messages.value.push({ user: username, text: text.value });
      createContent(null, username, text.value);
      text.value = '';
    }
  }
};

const createContent = (remoteUser, nowUser, text) => {
  let html;
  if (nowUser) {
    html = `<div class="el-row" style="padding: 5px 0">
              <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
                <div class="tip left">${text}</div>
              </div>
              <div class="el-col el-col-2">
                <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
              </div>
            </div>`;
  } else if (remoteUser) {
    html = `<div class="el-row" style="padding: 5px 0">
              <div class="el-col el-col-2" style="text-align: right">
                <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                  <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
              </div>
              <div class="el-col el-col-22" style="text-align: left; padding-left: 10px">
                <div class="tip right">${text}</div>
              </div>
            </div>`;
  }
  content.value += html;
};

const init = () => {
  if (typeof WebSocket === "undefined") {
    console.log("您的浏览器不支持WebSocket");
  } else {
    console.log("您的浏览器支持WebSocket");
    const socketUrl = `ws://localhost:8080/imserver/${username}`;
    if (socket.value != null) {
      socket.value.close();
      socket.value = null;
    }
    socket.value = new WebSocket(socketUrl);
    socket.value.onopen = () => {
      console.log("websocket已打开");
    };
    //每一次传消息都会调用onmessage
    socket.value.onmessage = (msg) => {
      console.log("收到数据====" + msg.data);
      const data = JSON.parse(msg.data);
      if (data.users) {
        users.value = data.users.filter(user => user.username !== username);
      } else {
        if (data.from === chatUser.value) {
          messages.value.push(data);
          createContent(data.from, null, data.text);
        }
      }
    };
    socket.value.onclose = () => {
      console.log("websocket已关闭");
    };
    socket.value.onerror = () => {
      console.log("websocket发生了错误");
    };
  }
};

onMounted(() => {
  init();
});
</script>
<style>
.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width:auto;
  display:inline-block !important;
  display:inline;
}
.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
